# 综合API测试脚本
# 测试智慧医疗RAG系统和医疗平台的所有API

Write-Host "=== 智慧医疗平台综合API测试 ===" -ForegroundColor Green
Write-Host "开始时间: $(Get-Date)" -ForegroundColor Cyan

# 配置
$ragApiUrl = "https://localhost:56704"
$readApiUrl = "https://localhost:5001"
$writeApiUrl = "https://localhost:5002"

# 测试结果统计
$testResults = @{
    Total = 0
    Passed = 0
    Failed = 0
    Errors = @()
}

function Test-ApiEndpoint {
    param(
        [string]$Name,
        [string]$Url,
        [string]$Method = "GET",
        [object]$Body = $null,
        [hashtable]$Headers = @{}
    )
    
    $testResults.Total++
    Write-Host "`n测试: $Name" -ForegroundColor Yellow
    Write-Host "URL: $Url" -ForegroundColor Gray
    
    try {
        $params = @{
            Uri = $Url
            Method = $Method
            SkipCertificateCheck = $true
        }
        
        if ($Body) {
            $params.Body = $Body | ConvertTo-Json -Depth 10
            $params.ContentType = "application/json"
        }
        
        if ($Headers.Count -gt 0) {
            $params.Headers = $Headers
        }
        
        $response = Invoke-WebRequest @params
        $content = $response.Content | ConvertFrom-Json
        
        Write-Host "✓ 成功" -ForegroundColor Green
        Write-Host "状态码: $($response.StatusCode)" -ForegroundColor Gray
        
        if ($content) {
            Write-Host "响应数据: $($content | ConvertTo-Json -Depth 3)" -ForegroundColor Gray
        }
        
        $testResults.Passed++
        return $content
    }
    catch {
        Write-Host "❌ 失败: $($_.Exception.Message)" -ForegroundColor Red
        $testResults.Failed++
        $testResults.Errors += "$Name`: $($_.Exception.Message)"
        return $null
    }
}

# 1. 测试智慧医疗RAG系统
Write-Host "`n=== 1. 智慧医疗RAG系统测试 ===" -ForegroundColor Magenta

# 1.1 测试主页
Test-ApiEndpoint -Name "RAG系统主页" -Url "$ragApiUrl/Home"

# 1.2 测试健康检查
Test-ApiEndpoint -Name "RAG系统健康检查" -Url "$ragApiUrl/api/Triage/health"

# 1.3 测试分诊分析 - 胸痛患者
$chestPainData = @{
    chiefComplaint = "剧烈胸痛，伴有胸闷和呼吸困难"
    symptoms = @("胸痛", "胸闷", "呼吸困难", "心悸", "出汗", "恶心")
    vitalSigns = @{
        bloodPressure = "160/100"
        heartRate = 120
        temperature = 37.2
        respiratoryRate = 24
        oxygenSaturation = 92
    }
    medicalHistory = "高血压病史5年，糖尿病病史3年"
    textData = "患者男性，65岁，主诉胸痛2小时，疼痛呈压榨性，向左臂放射，伴有出汗和恶心"
    voiceData = "base64编码的语音数据"
    imageData = "base64编码的胸部X光片"
    physiologicalData = @{
        type = "心电图"
        values = @(0.1, 0.2, 0.15, 0.3, 0.25)
        timestamps = @("2025-01-15T10:00:00Z", "2025-01-15T10:01:00Z", "2025-01-15T10:02:00Z", "2025-01-15T10:03:00Z", "2025-01-15T10:04:00Z")
        unit = "mV"
    }
}

Test-ApiEndpoint -Name "分诊分析-胸痛患者" -Url "$ragApiUrl/api/Triage/analyze" -Method "POST" -Body $chestPainData

# 1.4 测试分诊分析 - 头痛患者
$headacheData = @{
    chiefComplaint = "突发剧烈头痛，伴有右侧肢体无力"
    symptoms = @("头痛", "右侧肢体无力", "言语不清", "恶心", "呕吐", "意识模糊")
    vitalSigns = @{
        bloodPressure = "180/110"
        heartRate = 85
        temperature = 36.8
        respiratoryRate = 18
        oxygenSaturation = 96
    }
    medicalHistory = "高血压病史8年，房颤病史2年"
    textData = "患者女性，72岁，突发剧烈头痛，右侧肢体无力，言语不清，发病时间约30分钟"
}

Test-ApiEndpoint -Name "分诊分析-头痛患者" -Url "$ragApiUrl/api/Triage/analyze" -Method "POST" -Body $headacheData

# 2. 测试医疗平台读API
Write-Host "`n=== 2. 医疗平台读API测试 ===" -ForegroundColor Magenta

# 2.1 测试认证
$loginData = @{
    username = "doctor001"
    password = "password123"
}

$authResponse = Test-ApiEndpoint -Name "用户登录" -Url "$readApiUrl/api/Auth/login" -Method "POST" -Body $loginData

if ($authResponse -and $authResponse.token) {
    $headers = @{
        "Authorization" = "Bearer $($authResponse.token)"
    }
    
    # 2.2 测试咨询订单查询
    Test-ApiEndpoint -Name "查询咨询订单" -Url "$readApiUrl/api/ConsultationOrder/GetConsultationOrders" -Headers $headers
    
    # 2.3 测试医疗订单查询
    Test-ApiEndpoint -Name "查询医疗订单" -Url "$readApiUrl/api/MedicalOrder/GetMedicalOrders" -Headers $headers
    
    # 2.4 测试处方订单查询
    Test-ApiEndpoint -Name "查询处方订单" -Url "$readApiUrl/api/PrescriptionOrder/GetPrescriptionOrders" -Headers $headers
    
    # 2.5 测试退款申请查询
    Test-ApiEndpoint -Name "查询退款申请" -Url "$readApiUrl/api/RefundApplication/GetRefundApplications" -Headers $headers
    
    # 2.6 测试挂号订单查询
    Test-ApiEndpoint -Name "查询挂号订单" -Url "$readApiUrl/api/RegistrationOrder/GetRegistrationOrders" -Headers $headers
}

# 3. 测试医疗平台写API
Write-Host "`n=== 3. 医疗平台写API测试 ===" -ForegroundColor Magenta

# 3.1 测试用户注册
$registerData = @{
    username = "newuser001"
    password = "newpassword123"
    email = "newuser@example.com"
    phoneNumber = "13800138001"
    role = "Patient"
}

Test-ApiEndpoint -Name "用户注册" -Url "$writeApiUrl/api/User/Register" -Method "POST" -Body $registerData

# 3.2 测试创建咨询订单
$consultationData = @{
    patientId = "P001"
    doctorId = "D001"
    consultationType = "在线咨询"
    symptomDescription = "头痛，伴有恶心"
    appointmentTime = "2025-01-20T14:00:00Z"
    urgencyLevel = "一般"
}

Test-ApiEndpoint -Name "创建咨询订单" -Url "$writeApiUrl/api/Consultation/CreateConsultation" -Method "POST" -Body $consultationData

# 3.3 测试创建退款申请
$refundData = @{
    orderId = "PO001"
    patientId = "P001"
    refundReason = "药品过敏"
    refundAmount = 705.00
    applicationTime = "2025-01-16T10:00:00Z"
}

Test-ApiEndpoint -Name "创建退款申请" -Url "$writeApiUrl/api/RefundApplication/CreateRefundApplication" -Method "POST" -Body $refundData

# 4. 测试特殊场景
Write-Host "`n=== 4. 特殊场景测试 ===" -ForegroundColor Magenta

# 4.1 测试无效数据
$invalidData = @{
    chiefComplaint = ""
    symptoms = @()
}

Test-ApiEndpoint -Name "分诊分析-无效数据" -Url "$ragApiUrl/api/Triage/analyze" -Method "POST" -Body $invalidData

# 4.2 测试不存在的端点
Test-ApiEndpoint -Name "不存在的端点" -Url "$ragApiUrl/api/NonExistent"

# 4.3 测试无认证访问
Test-ApiEndpoint -Name "无认证访问" -Url "$readApiUrl/api/ConsultationOrder/GetConsultationOrders"

# 5. 性能测试
Write-Host "`n=== 5. 性能测试 ===" -ForegroundColor Magenta

$performanceData = @{
    chiefComplaint = "发热，伴有咳嗽和咽痛"
    symptoms = @("发热", "咳嗽", "咽痛", "流涕", "乏力")
    vitalSigns = @{
        bloodPressure = "120/75"
        heartRate = 85
        temperature = 38.8
        respiratoryRate = 18
        oxygenSaturation = 98
    }
    medicalHistory = "无特殊病史"
    textData = "患者男性，28岁，发热2天，伴有咳嗽、咽痛和流涕，无其他不适"
}

$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
Test-ApiEndpoint -Name "性能测试-分诊分析" -Url "$ragApiUrl/api/Triage/analyze" -Method "POST" -Body $performanceData
$stopwatch.Stop()
Write-Host "响应时间: $($stopwatch.ElapsedMilliseconds)ms" -ForegroundColor Cyan

# 6. 测试结果汇总
Write-Host "`n=== 测试结果汇总 ===" -ForegroundColor Green
Write-Host "总测试数: $($testResults.Total)" -ForegroundColor White
Write-Host "通过: $($testResults.Passed)" -ForegroundColor Green
Write-Host "失败: $($testResults.Failed)" -ForegroundColor Red
Write-Host "成功率: $([math]::Round(($testResults.Passed / $testResults.Total) * 100, 2))%" -ForegroundColor Cyan

if ($testResults.Errors.Count -gt 0) {
    Write-Host "`n错误详情:" -ForegroundColor Red
    foreach ($error in $testResults.Errors) {
        Write-Host "- $error" -ForegroundColor Red
    }
}

Write-Host "`n=== 测试完成 ===" -ForegroundColor Green
Write-Host "结束时间: $(Get-Date)" -ForegroundColor Cyan

# 保存测试结果到文件
$testReport = @{
    TestDate = Get-Date
    TotalTests = $testResults.Total
    PassedTests = $testResults.Passed
    FailedTests = $testResults.Failed
    SuccessRate = [math]::Round(($testResults.Passed / $testResults.Total) * 100, 2)
    Errors = $testResults.Errors
}

$testReport | ConvertTo-Json -Depth 10 | Out-File -FilePath "test-report-$(Get-Date -Format 'yyyyMMdd-HHmmss').json" -Encoding UTF8
Write-Host "测试报告已保存到: test-report-$(Get-Date -Format 'yyyyMMdd-HHmmss').json" -ForegroundColor Cyan 